<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Models\OrderLease;
use App\Models\OtherWithholdLog;
use App\Services\AlipayService;
use App\Services\CommonService;
use App\Services\OrderService;
use App\Services\RedisService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class WithholdCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'withholdOrder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '预授权定时扣款';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    protected function handleExec()
    {
        $this->withholdLease();
    }

    /**
     * 预授权定时扣款
     */
    public function withholdLease()
    {
        try {
            $leaseIds = RedisService::getRedisList(RedisService::REDIS_QUEUE_KEY_WITHHOLD_COUNT);
            if ($leaseIds) {
                $data = Order::from('sp_order_2 as o')
                    ->select('o.mini_id', 'o.biz_type', 'o.status as order_status', 'o.trade_no', 'o.rights_auth_no',
                        'o.payer_user_id', 'ol.id as leaseId', 'ol.which_period', 'ol.begin_time', 'ol.rent',
                        'ol.status', 'ol.withhold_status', 'og.goods_title', 'su.shopname')
                    ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->leftjoin('sp_shop_user_2 as su', 'o.seller_id', 'su.member_id')
                    ->whereIn('ol.id', $leaseIds)
                    ->get();
                $data = obToArray($data);
                foreach ($data as $item) {
                    if (
                        $item['withhold_status'] != OrderLease::LEASE_WITHHOLD_STATUS_NO
                        || !in_array($item['status'], [OrderLease::ORDER_LEASE_STATUS_NOPAY, OrderLease::ORDER_LEASE_STATUS_OVERDUE])
                        || !in_array($item['order_status'], OrderService::getOrderStatus(OrderService::ORDER_WITHHOLD_OR_PAY))
                    ) {
                        continue;
                    }

                    $miniId = intval($item['mini_id']);

                    $payData['orderNo'] = $item['trade_no'];
                    $payData['leaseId'] = $item['leaseId'];
                    $payData['authNo'] = $item['rights_auth_no'];
                    $payData['subject'] = '预授权转支付' . $item['goods_title'] . "|" . $item['shopname'];
                    $payData['totalAmount'] = $item['rent'];
                    $payData['userAlipayUId'] = $item['payer_user_id'];
                    $payData['billingDay'] = $item['begin_time'];
                    $payData['orderDescribe'] = '预授权解冻转支付第' . $item['which_period'] . '期' . '|' . $item['goods_title'] . '|' . $item['shopname'];
                    $payData['notifyUrl'] = config('alipay.callbackDomain') . CommonService::NOTICE_XXZ_URL_PRE_PAY;
                    $payRes = AlipayService::alipayPreToPay($miniId, $payData);
                    //查询是否有待履约的芝麻信用记录
                    $log_out_trade_no = isset($payRes['data']['out_trade_no']) ? $payRes['data']['out_trade_no'] : 0;
                    $log_trade_no = isset($payRes['data']['trade_no']) ? $payRes['data']['trade_no'] : 0;
                    OtherWithholdLog::orderWithholdLog($item['trade_no'], $item['leaseId'], $log_out_trade_no, $log_trade_no, $payRes['data'], OtherWithholdLog::PAY_TYPE_ZM, $payRes['status'], 1);
                }
                $this->infoLog('预授权定时扣款执行成功', $leaseIds);
            }
        } catch (\Exception $exception) {
            $this->infoLog('预授权定时扣款执行失败' . $exception->getMessage());
        }
    }
}
